/**
 * @param {character[][]} board
 * @param {string} word
 * @return {boolean}
 * 输入：board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出：true
 */
var exist = function (board, word) {
  let i = 0
  const codeObj = {}
  const len = board[0].length
  let result = false
  for (const key in board) {
    const item = board[key]
    for (const index in item) {
      codeObj[item[index]] ? codeObj[item[index]].push(i) : (codeObj[item[index]] = [i])
      item[index] = i
      i++
    }
  }
  if (word.length > i) {
    return false
  }
  const wordArr = word.split('').map(item => codeObj[item])
  const nextTap = (i, last, arr) => {
    if (i >= wordArr.length) {
      result = true
      console.log(arr)
      return
    }
    wordArr[i] &&
      wordArr[i].forEach((item, _) => {
        if (last === null || [1, len].includes(Math.abs(item - last))) {
          if (len > 1 && item - last === 1 && last % len === len - 1) {
            return
          }
          if (len > 1 && last - item === 1 && item % len === len - 1) {
            return
          }
          if (arr.includes(item)) {
            return
          } else {
            let c = i + 1
            nextTap(c, item, [...arr, item])
          }
        }
      })
  }
  nextTap(0, null, [])
  return result
}
console.log(
  exist(
    [
      ['A', 'B', 'C', 'E'],
      ['S', 'F', 'C', 'S'],
      ['A', 'D', 'E', 'E']
    ],
    'SEE'
  )
)
